package org.example.blockingQueue;

import java.text.SimpleDateFormat;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

// 特殊的阻塞队列
// 同步队列：不能存储,内部只能包含一个元素的队列
// 插入元素到队列的线程被阻塞，直到另一个线程从队列中获取了队列中存储的元素。
public class synchronousQueueDemo {

    public static void main(String[] args) {
        SynchronousQueue<String> synchronousQueue = new SynchronousQueue<>();

        new Thread(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + "放入：1");
                synchronousQueue.put("1");
                System.out.println(Thread.currentThread().getName() + "放入：2");
                synchronousQueue.put("2");
                System.out.println(Thread.currentThread().getName() + "放入：3");
                synchronousQueue.put("3");
                System.out.println(Thread.currentThread().getName() + "放入：4");
                synchronousQueue.put("4");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T1").start();

        new Thread(() -> {
            try {
                // 确保 T1 先执行（如果 T1 也在等待，则推出其阻塞）
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "取出：" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "取出：" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "取出：" + synchronousQueue.take());
                TimeUnit.SECONDS.sleep(3);
                System.out.println(Thread.currentThread().getName() + "取出：" + synchronousQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "T2").start();
    }
}
